<template>
  <div class="container">
    <!-- <div class="header">
      <div class="college-info">

        <span class="college-name">信息工程学院</span>
      </div>
      <div class="time-info">
        <span class="current-time">{{ currentTime }}</span>
        <span class="current-date">{{ currentDate }}</span>
      </div>
    </div> -->

    <div class="main-content">
      <div class="left-panel">
        <div class="card lab-card">
          <div class="card-header">

            <span class="lab-title">大语言模型创新实验室</span>
          </div>
          <div class="card-body lab-body">
            <div class="lab-meta-row">
              <div class="lab-meta">
                <span class="lab-label">场地类型</span>
                <span class="lab-value">计算机室</span>
              </div>
              <div class="lab-meta">
                <span class="lab-label">楼层</span>
                <span class="lab-value">3层</span>
              </div>
            </div>
            <div class="lab-meta-row">
              <div class="lab-meta">
                <span class="lab-label">房间号</span>
                <span class="lab-value">306</span>
              </div>
              <div class="lab-meta">
                <span class="lab-label">容纳人数</span>
                <span class="lab-value">80</span>
              </div>
            </div>
          </div>
        </div>

        <div class="card notice-card">
          <!-- 已添加标题前小椭圆 -->
          <div class="card-header">
            <span class="title-dot"></span>
            <span class="notice-title">通知公告</span>
          </div>
          <div class="card-body notice-body">
            <div class="notice-meta">
              <span class="notice-label">发布人</span>
              <span class="notice-value">教务处</span>
              <span class="notice-label">发布时间</span>
              <span class="notice-value">2025-09-12</span>
            </div>
            <div class="notice-content">
              <span class="notice-content-title">内容：</span>
              <span class="notice-content-text">关于本周实验课安排的通知，具体请查看附件内容，按时参加实验课。</span>
            </div>
          </div>
          <div class="card-footer notice-footer">
            <button class="page-btn prev">
              <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M11.5 14L7 9L11.5 4" stroke="#6a11cb" stroke-width="2.2" stroke-linecap="round"
                  stroke-linejoin="round" />
              </svg>
              上一条
            </button>
            <span class="page-info">1/1</span>
            <button class="page-btn next">
              下一条
              <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M6.5 4L11 9L6.5 14" stroke="#6a11cb" stroke-width="2.2" stroke-linecap="round"
                  stroke-linejoin="round" />
              </svg>
            </button>
          </div>
        </div>
      </div>

      <div class="right-panel">
        <div class="card schedule-card">
          <div class="card-header">
            <span class="title-dot"></span>
            <span class="card-title">大语言模型创新实验室</span>
            <span class="card-titles"> 当前周次: 第{{ todayZc || '-' }}周</span>
          </div>
          <div class="card-body">
            <!-- 星期选择器 -->
            <div class="week-selector">
              <button v-for="(day, index) in weekDays" :key="index" @click="handleWeekClick(index + 1)"
                :class="['day-btn', { 'active': selectedDay === index }]">
                {{ day }}
              </button>
            </div>

            <!-- 课程卡片容器 -->
            <div class="courses-container">
              <div class="course-item" v-for="(course, index) in filteredCourses" :key="index">
                <span class="course-section">第{{ course.jc }}节</span>
                <span class="course-name">{{ course.kc }}</span>
                <span class="teacher-time">
                  {{ course.syr }}<br>
                  {{ course.syrq }}<br>
                  {{ course.kkbj }}
                </span>
              </div>

              <!-- 无课程时显示 -->
              <div class="no-courses" v-if="filteredCourses.length === 0">
                当天没有安排课程
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="footer">
      <span class="footer-slogan">让每一节课都井然有序 · 智慧赋能校园</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { getYangoPaikeList } from '../api/index';
// 用于存放接口返回的数据
const yangoPaikeList = ref([]);
// 当前日期对应的周次
const todayZc = ref(null);
// 当前周次的所有数据
const todayZcList = ref([]);
// 星期数据
const weekDays = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日']);
const selectedDay = ref(0); // 默认选中周一
// 当前选中的日期（用 Date 对象便于计算）
const currentDate = ref(new Date());

// 课程数据 - 按星期几组织（动态填充）
// const courses = ref([ ... ]);
const courses = ref([[], [], [], [], [], [], []]);

// 根据选中的日期过滤课程
const filteredCourses = computed(() => {
  debugger
  console.log(selectedDay.value);
  console.log(courses.value);
  return courses.value[selectedDay.value] || [];
});

// 计算当前日期对应的"星期数字"（1=周一，7=周日）
const getCurrentWeekNum = () => {
  const nativeWeek = currentDate.value.getDay(); // 原生 JS 返回 0=周日，1=周一...6=周六
  return nativeWeek === 0 ? 7 : nativeWeek; // 转成 1-7：周日从 0 改成 7
};

// 格式化日期为"年-月-日"文本（用于页面显示）
const currentDateText = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = String(currentDate.value.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，补 0 成两位数
  const day = String(currentDate.value.getDate()).padStart(2, '0'); // 日期补 0 成两位数
  return `${year}-${month}-${day}`;
});

// 点击星期按钮的核心方法：传入目标星期数字，计算日期偏移
const handleWeekClick = (targetWeekNum) => {
  const currentWeekNum = getCurrentWeekNum(); // 当前星期（1-7）
  const dayOffset = targetWeekNum - currentWeekNum; // 日期偏移量（正数加，负数减）

  // 计算新日期：当前日期 + 偏移天数
  const newDate = new Date(currentDate.value);
  newDate.setDate(newDate.getDate() + dayOffset);

  // 更新当前日期
  currentDate.value = newDate;

  // 更新选中的星期索引（数组索引从0开始，所以减1）
  selectedDay.value = targetWeekNum - 1;

  // 重新获取课程数据
  loadCourseData();
};

// 选择日期（保留原有方法，用于兼容）
const selectDay = (index) => {
  selectedDay.value = index;
  // 根据选中的星期计算对应的日期
  const targetWeekNum = index + 1; // 数组索引转星期数字
  const currentWeekNum = getCurrentWeekNum();
  const dayOffset = targetWeekNum - currentWeekNum;

  const newDate = new Date(currentDate.value);
  newDate.setDate(newDate.getDate() + dayOffset);
  currentDate.value = newDate;

  // 重新获取课程数据
  loadCourseData();
};

// 时间相关
const currentTime = ref('');
const currentDateDisplay = ref('');

// 更新时间
const updateReload = () => {
  window.location.reload();
};

// 获取课程数据的独立方法
const loadCourseData = () => {
  // 获取当前选中日期的字符串格式
  const dateStr = currentDateText.value;

  // 查找该日期对应的周次（zc）
  const found = yangoPaikeList.value.find(item => item.syrq === dateStr);
  if (found) {
    todayZc.value = found.zc;
    // 查找所有周次等于该值的数据
    todayZcList.value = yangoPaikeList.value.filter(item => item.zc === todayZc.value);
    console.log('当前周次:', todayZc.value, '本周所有数据:', todayZcList.value);
    // 按星期（xq: 1-7）分类，组装成二维数组
    const weekArr = [[], [], [], [], [], [], []];
    todayZcList.value.forEach(item => {
      // xq: 1-7，weekArr索引0-6
      const idx = Number(item.xq) - 1;
      if (idx >= 0 && idx < 7) {
        weekArr[idx].push(item); // 直接推原始对象，保留所有字段
      }
    });
    // 按节次jc升序排序
    for (let i = 0; i < weekArr.length; i++) {
      weekArr[i].sort((a, b) => Number(a.jc) - Number(b.jc));
    }
    courses.value = weekArr;
  } else {
    // 如果当天没课，尝试从其他日期获取周次信息
    getWeekNumberFromOtherDates(dateStr);
    todayZcList.value = [];
    courses.value = [[], [], [], [], [], [], []];
  }
};

// 当当天没课时，从其他日期获取周次信息
const getWeekNumberFromOtherDates = (targetDate) => {
  // 方法1：查找最接近的日期来获取周次
  const sortedDates = yangoPaikeList.value
    .map(item => item.syrq)
    .filter(date => date) // 过滤掉空值
    .sort(); // 按日期排序

  if (sortedDates.length > 0) {
    // 找到最接近目标日期的日期
    let closestDate = sortedDates[0];
    let minDiff = Math.abs(new Date(targetDate) - new Date(closestDate));

    for (let date of sortedDates) {
      const diff = Math.abs(new Date(targetDate) - new Date(date));
      if (diff < minDiff) {
        minDiff = diff;
        closestDate = date;
      }
    }

    // 从最接近的日期获取周次
    const closestItem = yangoPaikeList.value.find(item => item.syrq === closestDate);
    if (closestItem) {
      // 计算目标日期与最接近日期的周次差值
      const targetDateObj = new Date(targetDate);
      const closestDateObj = new Date(closestDate);
      const daysDiff = Math.floor((targetDateObj - closestDateObj) / (1000 * 60 * 60 * 24));
      const weeksDiff = Math.floor(daysDiff / 7);

      todayZc.value = Number(closestItem.zc) + weeksDiff;
      console.log('从最接近日期获取周次:', closestDate, '周次:', closestItem.zc, '计算后周次:', todayZc.value);
    }
  }

  // 方法2：如果还是没找到，使用学期开始日期计算周次
  if (!todayZc.value) {
    calculateWeekFromSemesterStart(targetDate);
  }
};

// 根据学期开始日期计算周次（备用方法）
const calculateWeekFromSemesterStart = (targetDate) => {
  // 这里需要根据实际情况设置学期开始日期
  // 示例：假设2025年2月17日是第1周
  const semesterStartDate = '2025-02-17';
  const semesterStart = new Date(semesterStartDate);
  const target = new Date(targetDate);

  const timeDiff = target - semesterStart;
  const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
  const weekNumber = Math.floor(daysDiff / 7) + 1;

  if (weekNumber > 0) {
    todayZc.value = weekNumber;
    console.log('根据学期开始日期计算周次:', semesterStartDate, '目标日期:', targetDate, '计算周次:', weekNumber);
  } else {
    todayZc.value = 1; // 默认第1周
    console.log('使用默认周次: 1');
  }
};

// 页面加载时初始化
onMounted(() => {

  // 每秒更新一次时间
  setInterval(updateReload, 3600000);
  showCourseData();
});


const showCourseData = () => {
  // 设置当前日期为选中状态
  const today = new Date().getDay();
  // 周日在JS中是0，转为数组索引6
  const adjustedDay = today === 0 ? 6 : today - 1;
  selectedDay.value = adjustedDay;
  // 调用接口，不传参
  getYangoPaikeList().then(res => {
    yangoPaikeList.value = res.data;
    console.log('接口返回数据:', res.data);
    // 使用新的loadCourseData方法加载课程数据
    loadCourseData();
  }).catch(err => {
    console.error('接口请求失败:', err);
  });
}
</script>

<style scoped>
@import '../assets/HelloWorld.css';
</style>